<template>
  <div>
    <div class="query">
      <el-button type="primary" @click="handleAddRole(null)" v-has="'sys-menu-add'">新增一级菜单</el-button>
      <el-button type="success" @click="handleExpandAll">{{expandAllTxt}}</el-button>
    </div>

    <div class="table">
      <el-table
        v-if="refreshTable"
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        v-loading="tableLoading"
        :default-expand-all="expandAll"
        :tree-props="{ children: 'subs', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="title" align="center" label="名称" width="220" />
        <el-table-column align="center" prop="index" label="菜单url" />
        <el-table-column align="center" prop="icon" label="图标">
          <template #default="scope">
            <el-icon :size="20" v-if="scope.row.icon">
              <component :is="scope.row.icon"></component>
            </el-icon>
            <div v-else>无图标</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="component" label="组件名字" />
        <el-table-column align="center" prop="sort" label="排序" />
        <el-table-column align="center" prop="created_time" label="创建时间" />
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button
                v-if="scope.row.level == 0"
                type="text"
                size="small"
                @click.prevent="handleAddRole(scope.row)"
                v-has="'sys-menu-add'"
            >
              新增二级菜单
            </el-button>
            <el-button
                v-if="scope.row.level == 1"
                type="text"
                size="small"
                @click.prevent="handleAddRole(scope.row)"
                v-has="'sys-menu-add'"
            >
              新增按钮权限
            </el-button>
            <el-button
              type="text"
              size="small"
              @click.prevent="handleEditor(scope.row)"
              v-has="'sys-menu-edit'"
            >
              编辑
            </el-button>

            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="red"
              title="确定删除此菜单?"
              @confirm="handledeleteRow(scope.row)"
            >
              <template #reference>
                <el-button type="text" size="small" v-has="'sys-menu-del'"> 删除 </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      v-model="userState.treeDialogVisible"
      width="16%"
      :modal="false"
      :show-close="false"
      top="20px"
    >
      <el-tree
        ref="treeRef"
        :data="menuData"
        default-expand-all
        :props="defaultProps"
        @node-click="handleNodeClick"
        :expand-on-click-node="false"
      />
    </el-dialog>

    <el-dialog
      v-model="userState.dialogVisible"
      :title="userState.isAdd ? '新增' : '编辑'"
      width="40%"
      :before-close="handleClose"
    >
      <el-alert
        title="添加各级子权限请选择操作栏新增二级菜单或按钮"
        type="warning"
        style="margin-bottom: 10px"
      />
      <el-form
        ref="ruleFormRef"
        :rules="userState.rules"
        :model="userState.ruleForm"
        label-width="80px"
      >
        <div class="login-input">
          <el-form-item prop="level" label="类型">
            <el-radio-group
              v-model="userState.ruleForm.level"
              @change="handleRadioChange"
            >
              <el-radio disabled :label="0">目录</el-radio>
              <el-radio disabled :label="1">菜单</el-radio>
              <el-radio disabled :label="2">按钮</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item prop="title" label="名称">
            <el-input
              placeholder="请输入名称"
              v-model="userState.ruleForm.title"
              clearable
            />
          </el-form-item>

          <el-form-item prop="mark" label="上级菜单">
            <el-input
              placeholder="请选择上级菜单"
              readonly
              @click="handleFocus"
              v-model="userState.ruleForm.mark"
              clearable
              disabled
            />
          </el-form-item>

          <el-form-item prop="sort" label="排序号">
            <el-input-number v-model="userState.ruleForm.sort" :min="1" />
          </el-form-item>

          <el-form-item prop="icon" label="图标"  v-if="userState.ruleForm.level == 0">
            <!-- <el-input
              placeholder="请输入图标"
              v-model="userState.ruleForm.icon"
              clearable
            /> -->
            <icon-select v-model="userState.ruleForm.icon" />
          </el-form-item>

          <el-form-item prop="index" :label="userState.ruleForm.level == 2 ? '权限标记' : '菜单URL'">
            <el-input
              placeholder="请输入URL标记"
              v-model="userState.ruleForm.index"
              clearable
            />
          </el-form-item>
          <el-form-item prop="component" label="组件名" v-if="userState.ruleForm.level == 0">
            <el-input
              placeholder="请输入组件名"
              v-model="userState.ruleForm.component"
              clearable
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleDetermine(ruleFormRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, unref } from "vue";
import {
  queryAllPermissions,
  permissionDel,
  permissionAdd,
  permissionEdit,
} from "../../api/user";
import { InfoFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import { ElMessage } from "element-plus";
import IconSelect from "@/components/IconSelect.vue";

type FormInstance = InstanceType<typeof ElForm>;
const ruleFormRef = ref<FormInstance>();

interface User {
  id: number;
  created_time: string;
  mark: string;
  hasChildren?: boolean;
  subs?: User[];
}

onMounted(() => {
  handleGetAllMenu();
});

// 展开所有
const expandAll = ref(false)
const refreshTable = ref(true)
const expandAllTxt = ref("展开所有分类")

// 表格tableLoading
const tableLoading = ref(false);

const userState = reactive(<any>{
  treeDialogVisible: false,
  dialogVisible: false,
  isAdd: true,
  ruleForm: {
    fid: -1,
    title: "",
    index: "",
    component: "",
    sort: 1,
    mark: "",
    icon: "", // 图标
    level: 0, // 类型 0-一级 1-二级 2-按钮
  },
  // 表单校验
  rules: {
    title: [
      {
        required: true,
        message: "请输入名称",
        trigger: "blur",
      },
    ],
    sort: [],
    icon: [],
    index: [],
    level: [],
    mark: [],
    fid: [],
  },
});

// tree配置
const defaultProps = {
  children: "subs",
  label: "title",
};

const handleRadioChange = () => {
  userState.ruleForm.fid = -1;
  userState.ruleForm.title = "";
  userState.ruleForm.mark = "";
  userState.ruleForm.sort = 0;
  userState.ruleForm.icon = "";
  userState.ruleForm.index = "";
};

const handleNodeClick = (node: any) => {
  console.log(node);
  const level = userState.ruleForm.level;
  const { fid, id, mark, title } = node;
  // 如果选中节点为目录层
  console.log(level, title);
  if (level === 0 && title === "一级菜单") {
    userState.treeDialogVisible = false;
    userState.ruleForm.fid = 0;
    userState.ruleForm.mark = mark;
  } else if (level === 0 && title !== "一级菜单") {
    userState.treeDialogVisible = false;
  } else {
    console.log("title", title);
    console.log("id", id);
    console.log("mark", mark);
    if (title !== "一级菜单") {
      console.log("不是一级菜单");
      userState.treeDialogVisible = false;
      userState.ruleForm.fid = id;
      userState.ruleForm.mark = mark;
    } else {
      console.log("一级菜单");
      userState.treeDialogVisible = false;
    }
  }
};

const tableData = ref<User[]>([]);
const menuData = ref<any>([]);

const handleFocus = () => {
  userState.treeDialogVisible = true;
  console.log("handleFocus");
};

// 编辑获取对应菜单
const selectedArr = ref([]);

const handleGetAllMenu = () => {
  tableLoading.value = true;
  queryAllPermissions({}).then((res: any) => {
    console.log(res);
    if (res.code === 200) {
      const obj = {
        created_time: "",
        fid: 0,
        title: "一级菜单",
        mark: "一级菜单",
      };
      const result = [obj, ...res.data];
      tableData.value = res.data;
      menuData.value = result;
      tableLoading.value = false;
    }
  });
};

const editId = ref(-1);

const handleDetermine = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      const { id, title, mark, index, sort, icon, level, fid, component } =
        userState.ruleForm;
      const params = {
        id,
        fid,
        title,
        mark,
        index,
        sort,
        icon,
        level,
        component,
      };
      if (userState.ruleForm.fid == 0) {
        params.mark = params.title;
      }
      if (!userState.isAdd) params.id = editId.value;
      const data: any = userState.isAdd
        ? await permissionAdd(params)
        : await permissionEdit(params);
      if (data.code === 200) {
        handleGetAllMenu();
        userState.treeDialogVisible = false;
        userState.dialogVisible = false;
        ruleFormRef.value?.resetFields();
        ElMessage({
          message: `${userState.isAdd ? "新增" : "编辑"}菜单成功`,
          type: "success",
        });
        userState.isAdd = true;
      }
    }
  });
};

const handleClose = () => {
  const form = unref(ruleFormRef);
  form?.resetFields();
  // ruleFormRef.value.resetFields();
  userState.dialogVisible = false;
  userState.treeDialogVisible = false;
  console.log("handleClose");
};

const handleAddRole = (row: any) => {
  userState.dialogVisible = true;
  editId.value = -1;
  userState.isAdd = true;
  if(!row){
    userState.ruleForm.fid = 0;
    userState.ruleForm.mark = "一级菜单";
    userState.ruleForm.level = 0
  }else if(row && row.level == 0){
    userState.ruleForm.fid = row.id;
    userState.ruleForm.mark = row.title;
    userState.ruleForm.level = 1;
  }else if(row && row.level == 1){
    userState.ruleForm.fid = row.id;
    userState.ruleForm.mark = row.title;
    userState.ruleForm.level = 2
  }
  console.log("handleAddRole");
};

const handleEditor = async (row: any) => {
  console.log(row);
  editId.value = row.id;
  userState.isAdd = false;
  const { type, title, mark, index, sort, icon, level, fid, component } = row;
  userState.dialogVisible = true;
  await nextTick();
  userState.ruleForm.title = title;
  userState.ruleForm.index = index;
  userState.ruleForm.component = component;
  userState.ruleForm.sort = sort;
  userState.ruleForm.mark = mark;
  userState.ruleForm.icon = icon;
  userState.ruleForm.level = level;
  userState.ruleForm.fid = fid;
};

const handledeleteRow = ({ id }: any) => {
  permissionDel({ id }).then(({ code }: any) => {
    if (code === 200) {
      handleGetAllMenu();
      ElMessage({
        message: "删除菜单成功",
        type: "success",
      });
    }
  });
  console.log("handledeleteRow");
};

// 展开所有分类
const handleExpandAll = async () =>{
  refreshTable.value = false
  await nextTick()
  expandAll.value = !expandAll.value
  if(expandAll.value){
    expandAllTxt.value = "关闭所有分类"
  }else{
    expandAllTxt.value = "展开所有分类"
  }
  refreshTable.value = true
}
</script>
